﻿using OpenAiMobile.Tools;
using OpenAiMobile.Util.Database;
using OpenAiMobile.Util.Extensions;
using OpenAiMobile.Util.Services;

namespace OpenAiMobile.Services
{
    // ReSharper disable IdentifierTypo
    public class SqliteService : ISqliteService
    {
        private readonly string _connectionString;
        private readonly ILogService _logService;

        public SqliteService(ILogService logService)
        {
            _logService = logService;
            _connectionString = Constants.SQLite.GetConnectionString(FileSystem.Current.AppDataDirectory);
        }

        public async Task PrepareSqliteAsync()
        {
            var sqliteHelper = new SqliteHelper() { ConnectionString = _connectionString };
            await PrepareDatabaseAsync(sqliteHelper); //创建数据库
            await CreateTablesAsync(sqliteHelper); //创建表
        }

        private async Task PrepareDatabaseAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                await sqliteHelper.PrepareDatabaseAsync();
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService PrepareDatabaseAsync Exception: {e.GetFullMessage()}.");
            }
        }

        private async Task CreateTablesAsync(SqliteHelper sqliteHelper)
        {
            try
            {
                //配置表
                var sql = @"CREATE TABLE IF NOT EXISTS Config(
	                            Id VARCHAR(32) PRIMARY KEY,
	                            Key VARCHAR(256) NOT NULL,
                                Value TEXT,
	                            Description TEXT,
                                UpdateTime TEXT NOT NULL
                            );";
                await sqliteHelper.ExecuteNonQueryAsync(sql);
            }
            catch (Exception e)
            {
                // ReSharper disable once StringLiteralTypo
                _logService.Error($@"SqliteService CreateTablesAsync Exception: {e.GetFullMessage()}.");
            }
        }
    }
}
